﻿using Microsoft.Owin;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ldhWebApiWF
{
    public class CheckIPMiddleware : OwinMiddleware
    {
        public static List<string> IpWhitelist;
        public CheckIPMiddleware(OwinMiddleware next) : base(next) { }

        public async override Task Invoke(IOwinContext context)
        {
            //enable corss domain ajax access
            if (context.Request.Method == "OPTIONS")
            {
                await Next.Invoke(context);
                return;
            }

            if (IpWhitelist.FirstOrDefault() == "0.0.0.0/0")
            {
                await Next.Invoke(context);
                return;
            }

            if (IpWhitelist.Contains(context.Request.RemoteIpAddress))
            {
                await Next.Invoke(context);
                return;
            }
            context.Response.StatusCode = 429;
            await Task.FromResult<Object>(null);
        }
    }
}
